package com.atguigu.flink.chapter11;

import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.DataTypes;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.table.descriptors.Csv;
import org.apache.flink.table.descriptors.FileSystem;
import org.apache.flink.table.descriptors.Schema;

import static org.apache.flink.table.api.Expressions.$;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2022/1/22 10:35
 */
public class Flink03_Table_Connector_File {
    public static void main(String[] args) {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 20000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(1);
        
        StreamTableEnvironment tEnv = StreamTableEnvironment.create(env);
        
        Schema schema = new Schema()
            .field("id", DataTypes.STRING())
            .field("ts", DataTypes.BIGINT())
            .field("vc", DataTypes.INT());
        // 直接连接文件,. 得到一个动态表
        tEnv
            .connect(new FileSystem().path("input/sensor.txt"))
            .withFormat(new Csv().fieldDelimiter(',').lineDelimiter("\n"))  // 指定文件中数据的格式
            .withSchema(schema)  // 设置表的字段和类型
            .createTemporaryTable("sensor");  // 创建一个临时表(动态表)
        
        Table table = tEnv.from("sensor");
        Table result = table
            .where($("id").isEqual("sensor_1"))
            .select($("id"), $("ts"), $("vc"));
        
        // 创建一个动态表与sink'的文件进行关联
        tEnv
            .connect(new FileSystem().path("input/a.txt"))
            .withFormat(new Csv())
            .withSchema(schema)
            .createTemporaryTable("result_sensor");
        
        // 把result表的结果写入到表: result_sensor
        result.executeInsert("result_sensor");
        
    }
}
